<?php
session_start();

// 如用户已经登录，直接点击此页面将跳转回主页
if (isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

// 处理注册逻辑
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $confirmPassword = $_POST['confirm_password'];
    $email = trim($_POST['email']);

    // 验证输入
    $error_message = '';
    if (empty($username) || empty($password) || empty($email) || $password !== $confirmPassword) {
        $error_message = "用户名、密码或邮箱不能为空，且两次密码输入必须一致！";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error_message = "请输入有效的邮箱地址！";
    } else {
        // 连接数据库
        $host = 'localhost';
        $db   = 'dev_community';
        $user = 'root'; // 请替换为您的数据库用户名
        $pass = 'root'; // 请替换为您的数据库密码
        $charset = 'utf8mb4';

        $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
        $options = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ];

        try {
            $pdo = new PDO($dsn, $user, $pass, $options);
        } catch (\PDOException $e) {
            die("数据库连接失败: " . $e->getMessage());
        }

        // 检查用户名是否已存在
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$username]);
        if ($stmt->fetch()) {
            $error_message = "用户名已存在！";
        } else {
            // 密码加密
            $passwordHash = password_hash($password, PASSWORD_DEFAULT);

            // 插入新用户
            $stmt = $pdo->prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
            if ($stmt->execute([$username, $passwordHash, $email])) {
                // 注册成功，设置Session和Cookie
                $_SESSION['user_id'] = $pdo->lastInsertId();
                setcookie('user_id', $pdo->lastInsertId(), time() + 3600); // 1小时后过期
                header('Location: index.php');
                exit;
            } else {
                $error_message = "注册失败，请稍后再试。";
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智界论坛 - 用户注册</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
    <link rel="stylesheet" type="text/css" href="./css/qs.css"/>
    <link rel="stylesheet" type="text/css" href="./css/lg.css"/>
</head>

<body>
    <div class="loginBox1">
        <div class="header">
            <h2>智界论坛</h2>
            <a href="index.php" class="btn btn-link text-white">返回主页</a>
        </div>
        <form method="post" action="">
            <?php if (isset($error_message)): ?>
                <p class="error-message"><?php echo htmlspecialchars($error_message); ?></p>
            <?php endif; ?>
            <div class="item">
                <input type="text" name="username" required>
                <label for="username">用户名</label>
            </div>
            <div class="item">
                <input type="email" name="email" required>
                <label for="email">邮箱</label>
            </div>
            <div class="item">
                <input type="password" name="password" required>
                <label for="password">密码</label>
            </div>
            <div class="item">
                <input type="password" name="confirm_password" required>
                <label for="confirm_password">确认密码</label>
            </div>
            <div class="form-group">
                <button type="submit" class="btn">注册
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                </button>
            </div>
        </form>
    </div>

      <!-- 添加网页尾部 -->
<div class="footer">
    <p>&copy; 智界论坛·保留所有权利</p>
    <p>版权所有☆Qualan<sup>&copy;</sup> Q_L</p>
</div>
</body>

</html>